import type { RouteRecordRaw } from "vue-router"
function loadLocalRoutes() {
  //动态添加路由
  const localRoutes: RouteRecordRaw[] = []
  //读取路由所有文件
  const files: Record<string, any> = import.meta.glob(
    "../router/main/**/*.ts",
    {
      eager: true
    }
  )
  for (const key in files) {
    const module = files[key]
    localRoutes.push(module.default)
  }
  return localRoutes
}
export let fristMenu: any = null
export function mapMenusToRoutes(userMenus: any[]) {
  const localRoutes = loadLocalRoutes()
  // console.log(localRoutes)
  //根据菜单匹配正确的路由
  const routes: RouteRecordRaw[] = []

  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRoutes.find((item) => item.path === submenu.url)
      // console.log(route)
      if (route) {
        if (!routes.find((item) => item.path === menu.url)) {
          routes.push({ path: menu.url, redirect: route.path })
        }
        routes.push(route)
      }
      if (!fristMenu && route) {
        fristMenu = submenu
      }
    }
  }
  return routes
}

export function mapPathToMenu(path: string, userMenus: any[]) {
  for (const menu of userMenus) {
    // console.log(menu)
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu
      }
    }
  }
}

export function mapPathToBreadcrumbs(path: string, userMenus: any[]) {
  const breadcrumbs: any[] = []
  for (const menu of userMenus) {
    // console.log(menu)
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        // 顶层菜单
        breadcrumbs.push({ name: menu.name, path: menu.url })
        //
        breadcrumbs.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  // console.log(breadcrumbs)
  return breadcrumbs
}

// 菜单映射到id列表
export function mapMenusToIds(menusList:any[]){
      // for(const item1 of menusList){
      //   if(!item1.children) continue
      //   for(const item2 of item2){
      //     if(!item2.children) continue
      //     for(const item3 of item2){

      //     }
      //   }
      // }

      //递归
      const ids:number[]=[]
      function recurseGetId(menus:any[]){
        for(const item of menus){
          if(item.children){
            recurseGetId(item.children)
          }else{
            ids.push(item.id)
          }
        }
      }
      recurseGetId(menusList)
      return ids
}


export function mapMenuToPermissions(menusList:any[]){
const permissions:string[]=[]
 function recurseGetPermissions(menus:any[]){
  for(const item of menus){
    if(item.type===3) {
      permissions.push(item.permission)
    }else{
      recurseGetPermissions(item.children??[])
    }
  }
 }
 recurseGetPermissions(menusList)
return permissions
}
